#!/usr/bin/python

"""Template for your tron bot"""

import tron
import nn

import random
from operator import itemgetter
import sys
import time,struct

random.seed(time.time())

try:

	tmpfile = open(sys.argv[1])
	w = tmpfile.read()
	weights = struct.unpack('f'*(len(w)/4),w)

	nNet = nn.NN(weights)
except:
    nNet = nn.NN([ random.uniform(-0.5,0.5)  for i in xrange(328704)])
	

def symToFloat(board,x,y,test='#'):
    #try:
        if board[(x,y)] == test:
            return 1.0

        else :
            return -1.0
    #except:
    #    return 1.0



def which_move(board):

    # fill in your code here. it must return one of the following directions:
    #   tron.NORTH, tron.EAST, tron.SOUTH, tron.WEST

    # For now, choose a legal move randomly.
    # Note that board.moves will produce [NORTH] if there are no
    # legal moves available.

    meX,meY = board.me()
    themX,themY = board.them()
    x = meX -themX
    y= meY - themY
    d = (x)**2 + (y)**2
    
    nx,ny = (4,4)
    walls =  [symToFloat(board,x,y,'#') for x  in xrange(meX-nx,meX+ny) for y in xrange(meY-nx,meY+ny)]
    them =  [d/x,d/y,-d/x,-d/y]
    output = zip(nNet.update(walls+them),[1,2,3,4])

    sys.stderr.write(str(output)) 
    sys.stderr.write(str(board.moves())) 
    return  max([output[i-1] for i in board.moves()],key=itemgetter(0))[1]








# you do not need to modify this part
for board in tron.Board.generate():
    tron.move(which_move(board))
